﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using TripsLogic.controller;
using TripsLogic.util;
using System.Text;
using TripsLogic.model;

namespace TripsLogic
{
    public partial class profile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                checkLogInStatus();
                loadLang();
                initControls();
                loadUserInfo();

            }
            this.Title = LangController.getLng("litPersonalInfo.Text", "Personal Information");
            ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "autoinitialize();", true);
        }

        private void checkLogInStatus()
        {
            string restrictedPages = SysIniController.getSetting("Global_UserPages", "profile.aspx;change-password.aspx;trips.aspx;address.aspx");
            if (restrictedPages.Contains(System.IO.Path.GetFileName(Request.ServerVariables["SCRIPT_NAME"]).ToString()))
            {
                if (Session["Email"] == null || Session["Email"].ToString() == "")
                {
                    Session["RefUrl"] = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/')) +
                        Request.RawUrl;
                    Response.Redirect("log-in", true);
                }
            }
        }

        private void loadUserInfo()
        {
            if (Session["UserId"] != null)
            {
                DataTable dt = SysUserController.getUserById(Session["UserId"].ToString());
                if (dt != null && dt.Rows.Count >0)
                {
                    DataRow dr = dt.Rows[0];

                    // Load personal info
                    txtAlias.Text = dr["ALIAS"].ToString();
                    txtFirstName.Text = dr["FName"].ToString();
                    txtLastName.Text = dr["LNAME"].ToString();
                    string dateOfBirth = dt.Rows[0]["DOB"].ToString();
                    try
                    {
                        if (dateOfBirth != "")
                            txtDOB.Text = Common.parseDate(dateOfBirth, "yyyyMMddHHmmss").ToString("MM/dd/yyyy");
                    }
                    catch
                    {
                    }

                    if (dr["SEX"].ToString() != "True")
                        rblSex.SelectedIndex = 1;
                    else
                        rblSex.SelectedIndex = 0;

                    // Load contact info
                    txtMobile.Text = dr["MOBILE"].ToString();
                    txtPhone.Text = dr["PHONE"].ToString();
                    txtFax.Text = dr["FAX"].ToString();
                    txtEmail.Text = dr["EMAIL"].ToString();
                }
            }
        }

        private void initControls()
        {
            if (lblSexLang.Text != "")
            {
                string[] arrStringSex = lblSexLang.Text.Split(',');
                rblSex.Items[0].Text = arrStringSex[0];
                rblSex.Items[1].Text = arrStringSex[1];
            }
        }

        private void loadLang()
        {
            this.litPersonalInfo.Text = LangController.getLng("litPersonalInfo.Text", "Personal Information");
            this.litAlias.Text = LangController.getLng("litAlias.Text", "Alias");
            this.litFirstName.Text = LangController.getLng("litFirstName.Text", "First name");
            this.litLastName.Text = LangController.getLng("litLastName.Text", "Last name");
            this.litDOB.Text = LangController.getLng("litDOB.Text", "Date of birth");
            this.litSex.Text = LangController.getLng("litSex.Text", "Sex");
            this.lblSexLang.Text = LangController.getLng("lblSexLang.Text", "Male,Female");
            this.litContactInfo.Text = LangController.getLng("litContactInfo.Text", "Contact Information");
            this.litPhone.Text = LangController.getLng("litPhone.Text", "Phone");
            this.litFax.Text = LangController.getLng("litFax.Text", "Fax");
            this.litMobile.Text = LangController.getLng("litMobile.Text", "Mobile");
            this.litEmail.Text = LangController.getLng("litEmail.Text", "Email");
            this.litPersonalInfoDesc.Text = LangController.getLng("litPersonalInfo.Desc", "Some short description about personal information description. You need to fill in the following inputs: alias, firstname, lastname, date of birth, sex...");
            this.litContactInfoDesc.Text = LangController.getLng("litContactInfo.Desc", "Some short description about contact information description. You need to fill in the following inputs: phone, fax...");

            this.lbtSave.Text = LangController.getLng("litSave.Text", "Save");

            this.reqMobile.ErrorMessage = LangController.getLng("litRequired.Text", "(*)");
        }

        protected void lbtSave_Click(object sender, EventArgs e)
        {
            string script = getScript();
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "account", script, true);

            DateTime dtDOB;
            if (txtDOB.Text != "")
            {
                dtDOB = Common.strToFormatDateTime(txtDOB.Text, "MM/dd/yyyy");
            }

            SysUser user = new SysUser { 
                id = int.Parse(Session["UserId"].ToString()),
                alias = txtAlias.Text,
                fname = txtFirstName.Text,
                lname = txtLastName.Text,
                DOB = (txtDOB.Text == "" ? "" : Common.parseDate(txtDOB.Text, "MM/dd/yyyy").ToString("yyyyMMddHHmmss")),
                sex = rblSex.Items[0].Selected,
                phone = txtPhone.Text,
                fax = txtFax.Text,
                mobile = txtMobile.Text,
                roleId = -1
            };

            bool result = SysUserController.updateUser(user);

            if (result)
            {
                lblfrmResponse.ForeColor = System.Drawing.Color.Green;
                lblfrmResponse.Text = LangController.getLng("litSave.Ok", "Saved successfully");
            }
            else
            {
                lblfrmResponse.ForeColor = System.Drawing.Color.Red;
                lblfrmResponse.Text = LangController.getLng("litSave.Error", "Error occurs, please try again later.");
            }

            this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + lblfrmResponse.Text;
        }

        private string getScript()
        {
            StringBuilder result = new StringBuilder();
            result.Append("$(document).ready(function () {");
            result.Append("$('#content_txtDateOfBirth').datepicker({");
            result.Append("changeMonth: true,");
            result.Append("changeYear: true,");
            result.Append("yearRange: '1900:2020'");
            result.Append("    });");
            result.Append("});");
            return result.ToString();
        }
    }
}